﻿//    This file is part of EliteCollection.
//
//    EliteCollection is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    EliteCollection is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with EliteCollection.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DatabaseConnector;
using System.Text.RegularExpressions;
using System.Collections;
using EliteCollectionClasses;
using System.IO;
using EliteCollectionWindows;

namespace EliteCollectionSystem
{
    public partial class MainWnd : Form
    {
        public DatabaseConnector.DatabaseConnector databaseHandler;
        public Hashtable dataHash = new Hashtable();
        public Hashtable databasesHash = new Hashtable();
        public String currentDataFilePath = "";
        public MainWnd()
        {
            InitializeComponent();
        }

        private void MainWnd_Load(object sender, EventArgs e)
        {
            //Activate Logger
            Program.logger = new LogWnd();
            Program.logger.Visible = false;
            Program.logger.Enabled = true;
            Program.logger.addLog("Program Started Successfully!");
            //Get Database Data
            databaseHandler = new DatabaseConnector.DatabaseConnector();
            Program.logger.addLog("Database Handler Created!");
            connectDatabase(Environment.CurrentDirectory + "\\databases\\example.ecsd");
        }

        private void connectDatabase(string path)
        {
            currentDataFilePath = path;
            items.Columns.Clear();
            items.Items.Clear();
            FlatConn database = databaseHandler.connect(path);
            Program.logger.addLog("Connected to Database!");
            //Write DatabaseConnection Debug
            Program.logger.addLog(database.databaseFile);
            Program.logger.addLog("==========Columns==========");
            foreach (string item in database.columns)
            {
                items.Columns.Add(item);
                Program.logger.addLog(item);
            }
            Program.logger.addLog("==========Rows==========");
            foreach (string item in database.rows)
            {
                items.Items.Add(new ListViewItem(parseItem(item)));
                Program.logger.addLog(item);
            }
            foreach (ColumnHeader column in items.Columns)
            {
                column.Width = 100;
            }
            //Add to database list
            FileInfo tempfileinfo = new FileInfo(path);
            databases.Items.Add(tempfileinfo.Name.Replace(tempfileinfo.Extension, ""));
            databasesHash.Add(tempfileinfo.Name.Replace(tempfileinfo.Extension, ""), path);
            //Create DataObject for Database
            EliteCollectionClasses.DataObject tempDataObject = new EliteCollectionClasses.DataObject();
            tempDataObject.listViewHeaders = items.Columns;
            foreach (ColumnHeader columnhead in items.Columns)
            {
                tempDataObject.listViewHeadersArray.Add(columnhead);
            }
            tempDataObject.listViewItems = items.Items;
            foreach (ListViewItem item in items.Items)
            {
                tempDataObject.listViewItemsArray.Add(item);
            }
            //Add DataObject to Array
            dataHash.Add(path, tempDataObject);
            databases.SelectedIndex = databases.Items.Count - 1;
        }

        private string[] parseItem(string input)
        {
            string[] tempReturn = Regex.Split(input, "<->");
            return tempReturn;
        }

        private void loggerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.logger.Visible = true;
        }

        private void saveDataObject(EliteCollectionClasses.DataObject input, String path)
        {
            //Clear old Database Data
            File.Delete(path);
            //Write New Data
            String prehead = "";
            String prebody = "";
            //Setup Head
            int headindex = 0;
            foreach (ColumnHeader head in input.listViewHeadersArray)
            {
                if (headindex != input.listViewHeadersArray.Count)
                {
                    prehead += head.Text + "				";
                }
                else
                {
                    prehead += head.Text;
                }

                headindex += 1;
            }
            File.AppendAllText(path, prehead + Environment.NewLine);
            //Setup Body
            int bodyindex = 0;
            ArrayList itemLines = new ArrayList();
            foreach (ListViewItem item in input.listViewItemsArray)
            {
                int tempItemIndex = 0;
                String tempItemLine = "";
                foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                {
                    if (tempItemIndex != item.SubItems.Count)
                    {
                        tempItemLine += subitem.Text + "				";
                    }
                    else
                    {
                        tempItemLine += subitem.Text;
                    }

                    tempItemIndex += 1;
                }
                File.AppendAllText(path, tempItemLine + Environment.NewLine);

                bodyindex += 1;
            }
        }

        private void databases_SelectedValueChanged(object sender, EventArgs e)
        {
            //Delete old Current DataObject
            dataHash.Remove(currentDataFilePath);
            //Save Current DataObject
            EliteCollectionClasses.DataObject tempDataObject = new EliteCollectionClasses.DataObject();
            tempDataObject.listViewHeaders = items.Columns;
            foreach (ColumnHeader columnhead in items.Columns)
            {
                tempDataObject.listViewHeadersArray.Add(columnhead);
            }
            tempDataObject.listViewItems = items.Items;
            foreach (ListViewItem item in items.Items)
            {
                tempDataObject.listViewItemsArray.Add(item);
            }
            dataHash.Add(currentDataFilePath, tempDataObject);
            //Switch to Selected DataObject.
            EliteCollectionClasses.DataObject selectedDataObject = (EliteCollectionClasses.DataObject)dataHash[databasesHash[databases.Items[databases.SelectedIndex].ToString()].ToString()];
            items.Items.Clear();
            items.Columns.Clear();
            foreach (ColumnHeader column in selectedDataObject.listViewHeadersArray)
            {
                items.Columns.Add(column);
            }
            foreach (ListViewItem lvItem in selectedDataObject.listViewItemsArray)
            {
                items.Items.Add(lvItem);
            }
            currentDataFilePath = databasesHash[databases.Items[databases.SelectedIndex].ToString()].ToString();
        }

        private void connectToDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog tempOpenFile = new OpenFileDialog();
            if (tempOpenFile.ShowDialog() == DialogResult.OK)
            {
                connectDatabase(tempOpenFile.FileName);
            }
        }

        private void newDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog tempSaveFile = new SaveFileDialog();
            tempSaveFile.Filter = "Elite Collection System Database (*.ecsd)|*.ecsd";
            if (tempSaveFile.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(tempSaveFile.FileName, "Name				File Name				Full Path								Size		Length\n");
                connectDatabase(tempSaveFile.FileName);
            }
        }

        private void addToSelectedDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Add Media/Media Folder
            twoansquestion tempQuestion = new twoansquestion("Where do you want to add media from", "Folder", "Files", "Ok");
            DialogResult result = tempQuestion.ShowDialog();
            FolderBrowserDialog fbd;
            OpenFileDialog ofd;
            switch (result)
            {
                case DialogResult.Yes:
                    //First Answer (Folder)
                    fbd = new FolderBrowserDialog();
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        string[] files = Directory.GetFiles(fbd.SelectedPath,"*",SearchOption.AllDirectories);
                        foreach (string file in files)
                        {
                            //Get FileName, Extension, Length
                            FileInfo tempFileInfo = new FileInfo(file);
                            //Get File Duration
                            Microsoft.DirectX.AudioVideoPlayback.Video video = null;
                            try
                            {
                                video = new Microsoft.DirectX.AudioVideoPlayback.Video(file);
                            }
                            catch (Microsoft.DirectX.DirectXException ex)
                            {

                            }
                            TimeSpan durtime = new TimeSpan();
                            try
                            {
                                durtime = TimeSpan.FromSeconds(video.Duration);
                            }
                            catch (Exception ex)
                            {

                            }
                            //Add to string array
                            string[] tempStrings = { tempFileInfo.Name + tempFileInfo.Extension, tempFileInfo.Name, file, (Math.Round((tempFileInfo.Length / 1024f) / 1024f)).ToString() + "MB", durtime.Hours.ToString() + ":" + durtime.Minutes.ToString() + ":" + durtime.Seconds.ToString() };
                            //add to database
                            items.Items.Add(new ListViewItem(tempStrings));
                        }
                    }
                    break;
                case DialogResult.No:
                    //Second Answer (File)
                    ofd = new OpenFileDialog();
                    ofd.Multiselect = true;
                    ofd.Filter = "Video Files (*.avi,*.wmv,*.mpg) |*.avi;*.wmv;*.mpg|Audio Files (*.wma, *.mp3) |*.wma;*.mp3|All Files (*.*) |*.*";
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        foreach (string file in ofd.FileNames)
                        {
                            //Get FileName, Extension, Length
                            FileInfo tempFileInfo = new FileInfo(file);
                            //Get File Duration
                            Microsoft.DirectX.AudioVideoPlayback.Video video = new Microsoft.DirectX.AudioVideoPlayback.Video(file);
                            TimeSpan durtime = TimeSpan.FromSeconds(video.Duration);
                            //Add to string array
                            string[] tempStrings = { tempFileInfo.Name + tempFileInfo.Extension, tempFileInfo.Name, file, (Math.Round((tempFileInfo.Length / 1024f) / 1024f)).ToString() + "MB", durtime.Hours.ToString() + ":" + durtime.Minutes.ToString() + ":" + durtime.Seconds.ToString() };
                            //add to database
                            items.Items.Add(new ListViewItem(tempStrings));
                        }
                    }
                    break;
            }
        }

        private void items_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem selectedItem = items.SelectedItems[0];
            try
            {
                vlc.playlist.stop();
            }
            catch (Exception ex) { }
            vlc.playlist.clear();
            vlc.playlist.add(selectedItem.SubItems[2].Text, selectedItem.SubItems[0].Text, new object());
            vlc.playlist.play();
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            vlc.playlist.stop();
        }

        private void MainWnd_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (string database in databases.Items)
            {
                //Get DataObject and Path.
                EliteCollectionClasses.DataObject savingDataObject = (EliteCollectionClasses.DataObject)dataHash[databasesHash[databases.Items[databases.Items.IndexOf(database)].ToString()].ToString()];
                String database_path = databasesHash[databases.Items[databases.Items.IndexOf(database)].ToString()].ToString();
                EliteCollectionClasses.DataObject database_obj = savingDataObject;
                
                //Refresh Current DataObject
                dataHash.Remove(currentDataFilePath);
                //Save Current DataObject
                EliteCollectionClasses.DataObject tempDataObject = new EliteCollectionClasses.DataObject();
                tempDataObject.listViewHeaders = items.Columns;
                foreach (ColumnHeader columnhead in items.Columns)
                {
                    tempDataObject.listViewHeadersArray.Add(columnhead);
                }
                tempDataObject.listViewItems = items.Items;
                foreach (ListViewItem item in items.Items)
                {
                    tempDataObject.listViewItemsArray.Add(item);
                }
                dataHash.Add(currentDataFilePath, tempDataObject);

                //Save Database
                saveDataObject(database_obj, database_path);
            }
        }

        private void items_randomplay_Click(object sender, EventArgs e)
        {
            int rand = Tools.RandomNumber(0, items.Items.Count);
            ListViewItem selectedItem = items.Items[rand];
            int index = vlc.playlist.add(selectedItem.SubItems[2].Text, selectedItem.SubItems[0].Text, new object());
            vlc.playlist.playItem(index);
        }
    }
}
